//
//  XDGridView.m
//  XDHoHo
//
//  Created by xie yajie on 13-11-16.
//  Copyright (c) 2013年 XD. All rights reserved.
//

#import "XDGridView.h"

#define kDefaultBorderWidth     5.0
#define kDefaultBorderHeight    5.0

@interface XDGridView ()
{
    NSMutableArray *_itemsArray;
    
    UIPageControl *_pageControl;
    BOOL _pageControlUsed;
}
@end

@implementation XDGridView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _itemsArray = [[NSMutableArray alloc] init];
        
        _selectedIndex = -1;
        
        _borderWidth = kDefaultBorderWidth;
        _borderHeight = kDefaultBorderHeight;
        
        _enableLongPress = NO;
        _enableSinglePress = YES;
        _enableDoubleTap = NO;
        _pageControlUsed = YES;
    }
    return self;
}



#pragma mark - Subview Methods

/*重绘全部item*/
- (void)reloadData
{
    //更新布局参数
    _numberOfItems = [_dataSource numberOfItemsInGridView:self];
    if ([_dataSource respondsToSelector:@selector(gridView:numberOfRowsInPage:)]) {
        _numberOfRows = [_dataSource gridView:self numberOfRowsInPage:0];
    }
    if ([_dataSource respondsToSelector:@selector(gridView:numberOfColumnsInRow:page:)]) {
        _numberOfColumns = [_dataSource gridView:self numberOfColumnsInRow:0 page:0];
    }
    _numberOfPages = ceilf((float)_numberOfItems / (float)(_numberOfRows * _numberOfColumns));
    
    _widthOfItem = (self.frame.size.width - (_numberOfColumns + 1) * _borderWidth) / _numberOfColumns;
    _heightOfItem = (self.frame.size.height - (_numberOfRows + 1) * _borderHeight) / _numberOfRows;
    
    //重绘布局
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.delegate = self;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.pagingEnabled = YES;
        [self addSubview:_scrollView];
    }
    _scrollView.frame = self.bounds;
    _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * _numberOfPages, _scrollView.frame.size.height);
    
    [_itemsArray makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [_itemsArray removeAllObjects];
    
    for (NSUInteger i = 0; i < _numberOfItems; i++) {
        NSInteger itemPage = i / (_numberOfRows * _numberOfColumns);
        NSInteger itemRow = i / _numberOfColumns % _numberOfRows;
        NSInteger itemColumn = i % _numberOfColumns;
        
        CGFloat x = _borderWidth + itemColumn * (_widthOfItem + _borderWidth) + _scrollView.frame.size.width * itemPage;
        CGFloat y = _borderHeight + itemRow * (_heightOfItem + _borderHeight);
        
//        XDGridViewItem *item = [[XDGridViewItem alloc] initWithFrame:CGRectMake(x, y, _widthOfItem, _heightOfItem)];
        XDGridViewItem *item = [[XDGridViewItem alloc] initWithFrame:CGRectMake(x, y, _widthOfItem, _heightOfItem) style:_itemStlye];
        item.index = i;
        item.page = itemPage;
        item.row = itemRow;
        item.column = itemColumn;
        item.backgroundColor = [UIColor clearColor];
        
        if ([_dataSource respondsToSelector:@selector(gridView:setupItem:)]) {
            [_dataSource gridView:self setupItem:item];
        }
        
        //触控事件
        UITapGestureRecognizer *singleTapGesture = nil;
        if (_enableSinglePress) {//允许单击监听
            singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didSingleTapItem:)];
            singleTapGesture.numberOfTapsRequired = 1;
            [item addGestureRecognizer:singleTapGesture];
        }
        
        if (_enableLongPress) {//允许长按监听
            UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(didLongPressItem:)];
            longPressGesture.numberOfTouchesRequired = 1;
            [item addGestureRecognizer:longPressGesture];
        }
        
        if (_enableDoubleTap) {//允许双击监听
            UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didDoubleTapItem:)];
            doubleTapGesture.numberOfTapsRequired = 2;
            doubleTapGesture.delaysTouchesBegan = YES;
            [item addGestureRecognizer:doubleTapGesture];
            
            singleTapGesture.delaysTouchesBegan = YES;
            [singleTapGesture requireGestureRecognizerToFail:doubleTapGesture];
        }
        
        [_scrollView addSubview:item];
        [_itemsArray addObject:item];
    }
    
    _pageControl.numberOfPages = _numberOfPages;
}

- (UIPageControl *)pageControl
{    
    if (!_pageControl) {
        CGRect frame = self.frame;
        frame.origin.y += frame.size.height;
        frame.size.height = 36.0;
        _pageControl = [[UIPageControl alloc] initWithFrame:frame];
        _pageControl.numberOfPages = _numberOfPages;
        _pageControl.currentPage = 0;
        [_pageControl addTarget:self action:@selector(scrollToCurrentPage) forControlEvents:UIControlEventValueChanged];
    }
    return _pageControl;
}

/*重绘指定item的视图*/
- (void)reloadItemsAtIndexs:(NSArray *)indexs withItemAnimation:(XDGridViewItemAnimation)animation
{
    
}

/*当前可见item的视图数组*/
- (NSArray *)visibleViews
{
    return nil;
}

/*当前可见item的index数组*/
- (NSArray *)visibleIndexs
{
    return nil;
}

/*获取指定item*/
- (XDGridViewItem *)itemAtIndex:(NSUInteger)index
{
    return (index < _itemsArray.count) ?  [_itemsArray objectAtIndex:index] : nil;
}



#pragma mark - Selected Item

- (void)setSelectedIndex:(NSInteger)selectedIndex
{
    if (_selectedIndex >= 0 && _selectedIndex < _itemsArray.count) {//存在已选中item
        [[_itemsArray objectAtIndex:_selectedIndex] setIsSelected:NO];
    }
    
    _selectedIndex = selectedIndex;
    
    if (_selectedIndex >= 0 && _selectedIndex < _itemsArray.count) {//选中指定item
        [[_itemsArray objectAtIndex:_selectedIndex] setIsSelected:YES];
    }
}



#pragma mark - Gesture

/*长按事件*/
- (void)didLongPressItem:(UILongPressGestureRecognizer *)longPressGesture
{
    if (longPressGesture.state == UIGestureRecognizerStateBegan) {
        if ([_delegate respondsToSelector:@selector(gridView:didBeginLongPressItem:)]) {
            [_delegate gridView:self didBeginLongPressItem:(XDGridViewItem *)longPressGesture.view];
        }
    } else if (longPressGesture.state == UIGestureRecognizerStateRecognized) {
        if ([_delegate respondsToSelector:@selector(gridView:didEndLongPressItem:)]) {
            [_delegate gridView:self didEndLongPressItem:(XDGridViewItem *)longPressGesture.view];
        } else if ([_delegate respondsToSelector:@selector(gridView:didSelectItem:)]) {
            [_delegate gridView:self didSelectItem:(XDGridViewItem *)longPressGesture.view];
        }
    }
}

/*双击事件*/
- (void)didDoubleTapItem:(UITapGestureRecognizer *)doubleTapGesture
{
    if (doubleTapGesture.state == UIGestureRecognizerStateRecognized) {
        if ([_delegate respondsToSelector:@selector(gridView:didDoubleTapItem:)]) {
            [_delegate gridView:self didDoubleTapItem:(XDGridViewItem *)doubleTapGesture.view];
        } else if ([_delegate respondsToSelector:@selector(gridView:didSelectItem:)]) {
            [_delegate gridView:self didSelectItem:(XDGridViewItem *)doubleTapGesture.view];
        }
    }
}

/*单击事件*/
- (void)didSingleTapItem:(UITapGestureRecognizer *)singleTapGesture
{
    if (singleTapGesture.state == UIGestureRecognizerStateRecognized) {        
        XDGridViewItem *item = (XDGridViewItem *)singleTapGesture.view;
        self.selectedIndex = item.index;
        
        if ([_delegate respondsToSelector:@selector(gridView:didSingleTapItem:)]) {
            [_delegate gridView:self didSingleTapItem:item];
        } else if ([_delegate respondsToSelector:@selector(gridView:didSelectItem:)]) {
            [_delegate gridView:self didSelectItem:item];
        }
    }
}



#pragma mark - ScrollView Delegate & Methods

/*滚动至指定item*/
- (void)scrollToItemAtIndex:(NSUInteger)index animated:(BOOL)animated
{
    
}

/*跳转到当前页面*/
- (void)scrollToCurrentPage
{
    CGRect frame = _scrollView.frame;
    frame.origin.x = frame.size.width * _pageControl.currentPage;
    [_scrollView scrollRectToVisible:frame animated:YES];
    
    _pageControlUsed = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_pageControlUsed) {
        return;
    }
	
    CGFloat pageWidth = scrollView.frame.size.width;
    NSInteger page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    _pageControl.currentPage = page;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _pageControlUsed = NO;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _pageControlUsed = NO;
}

@end
